// src/interceptors/response.interceptor.ts
import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface Response<T> {
  code: number;
  message: string;
  data: T | null; // 允许 data 为 null
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    const ctx = context.switchToHttp();
    const response = ctx.getResponse();

    return next.handle().pipe(
      map((data) => {
        // 定义明确的返回类型
        const result: Response<T> = {
          code: response.statusCode,
          message: 'success',
          data: null,
        };

        if (data && typeof data === 'object' && 'message' in data) {
          result.message = data.message as string;
          result.data = 'data' in data ? (data.data as T) : null;
        } else {
          result.data = (data as T) ?? null;
        }

        return result;
      }),
    );
  }
}
